<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import PageContainer from "@/components/PageContainer.vue";
import {addArticle, uploadImage} from "@/api/article.js";
import {ElMessage} from "element-plus";
import {sysUserEditService} from "@/api/sys_user.js";

const userStore = useUserStore()

const {getUser} = useUserStore()
const id = ref(userStore.user.id)
const imgUrl = ref(userStore.user.avatar)
const imgFile = ref()

const uploadRef = ref()
const onUploadFile = (file) => {
	const reader = new FileReader()
	reader.readAsDataURL(file.raw)
	reader.onload = () => {
		imgUrl.value = reader.result
		imgFile.value = file.raw
	}
}
const onSelect = async () => {
	const fd = new FormData()
	fd.append('file', imgFile.value)
	const {data: filePath} = await uploadImage(fd)
	await sysUserEditService({
		id: id.value,
		avatar: filePath
	})
	ElMessage.success('上传成功')
	getUser()
}
</script>

<template>
	<page-container title="更换头像">
		<el-row>
			<el-col :span="12">
				<el-upload
						class="avatar-uploader"
						:auto-upload="false"
						:show-file-list="false"
						:on-change="onUploadFile"
						ref="uploadRef"
				>
					<img v-if="imgUrl" :src="imgUrl" class="avatar"  alt=""/>
					<img v-else src="@/assets/avatar.jpg" width="350" alt=""/>
				</el-upload>
				<br />
				<!--可以通过 $el 拿到 dom 元素-->
				<el-button
						@click="uploadRef.$el.querySelector('input').click()"
						type="primary" :icon="Plus" size="large">
					选择图片
				</el-button>
				<el-button type="success" :icon="Upload" size="large" @click="onSelect">
					上传头像
				</el-button>
			</el-col>
		</el-row>
	</page-container>
</template>

<style lang="scss" scoped>
.avatar-uploader {
	:deep {
		.avatar {
			width: 278px;
			height: 278px;
			display: block;
		}
		.el-upload {
			border: 1px dashed var(--el-border-color);
			border-radius: 6px;
			cursor: pointer;
			position: relative;
			overflow: hidden;
			transition: var(--el-transition-duration-fast);
		}
		.el-upload:hover {
			border-color: var(--el-color-primary);
		}
		.el-icon.avatar-uploader-icon {
			font-size: 28px;
			color: #8c939d;
			width: 278px;
			height: 278px;
			text-align: center;
		}
	}
}
</style>